import React, { useEffect, useState } from 'react'
import { Button, Upload } from 'antd'
import { UploadChangeParam, UploadFile } from 'antd/es/upload'
import axios from 'axios'

const Index: React.FC = () => {
  // 存储路径
  const [urls, setUrls] = useState<string[]>([])
  // 上传事件
  const onChange = (info: UploadChangeParam<UploadFile<any>>) => {
    // 是否有返回结果
    if (info.file.response) {
      const { code, data } = info.file.response;
      // 保存返回结果
      if (code === 200) {
        // 注意：依赖上一次结果， 使用函数写法， 否则出现bug
        // setUrls(url => {
        //   return [...url, data]
        // })
        setUrls([...urls, data])
      }
    }
  }
  // 获取数据
  const fetchUrlsList = async () => {
    const resp = await axios.get('/api/upload/list')
    setUrls(resp.data.data)
  }
  useEffect(() => {
    fetchUrlsList()
  }, [])

  const handleDelete = (name: string) => {
    const data = name.split('/').pop();

    axios.delete('/api/upload/' + data).then(() => {
      fetchUrlsList()
    })

  }
  return (
    <div>
      <Upload.Dragger multiple action="/api/upload/koa" onChange={onChange} itemRender={() => <div></div>}>
        <h2>拖拽进入区域上传</h2>
        <Button type="primary">上传文件</Button>
      </Upload.Dragger>
      <div style={{ display: 'flex', flexWrap: 'wrap'}}>
        {
          urls.map((v, i) => {
            return <div style={{ position: 'relative' }} key={i}>
              <span onClick={() => handleDelete(v)} style={{ position: 'absolute', right: 2, top: 2, zIndex: 10 }}>X</span>
              <img src={v} height={100} alt="" key={i} style={{ margin: 10 }} />
              <div>
                <a href={v + '?response-content-type=application/octet-stream'} download target="downloadFile">下载</a>
              </div>
            </div>
          })
        }
      </div>
    </div>
  )
}

export default Index